package com.sunxueqi.framework.security.handler;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Service;

import com.sunxueqi.common.util.ServletUtils;
import com.sunxueqi.framework.security.LoginUser;
import com.sunxueqi.framework.security.service.TokenService;
import com.sunxueqi.framework.web.vo.ResponseData;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;

@Configuration
@Service("logoutSuccessHandlerImpl")
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler{
	
	@Autowired
	private TokenService tokenService;

	/**
	 * 退出登录的相关处理
	 */
	@Override
	public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		LoginUser loginUser = tokenService.getLoginUser(request);
		if(ObjectUtil.isNotNull(loginUser)) {
			// String username = loginUser.getUsername();
			// 删除用户token
			tokenService.deleteLoginUser(loginUser.getToken());
		}
		ServletUtils.renderString(response, JSONUtil.toJsonStr(ResponseData.error(HttpStatus.OK, "退出登录成功")));
	}
	
}
